package cn.lingyangwl.agile.common.feign.interceptor;

import cn.lingyangwl.agile.model.constants.RequestCons;
import cn.lingyangwl.agile.model.constants.SecurityCons;
import cn.lingyangwl.agile.model.module.auth.LoginUserHolder;
import cn.lingyangwl.agile.model.module.tenant.TenantContext;
import cn.lingyangwl.framework.core.utils.servlet.ServletUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.http.HttpHeaders;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * feign 请求拦截器 oauth2 feign token传递
 *
 * @author shenguangyang
 */
@RequiredArgsConstructor
@ConditionalOnClass({FeignAutoConfiguration.class})
public class FeignOauth2RequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        Collection<String> authorization = template.headers().get(HttpHeaders.AUTHORIZATION);
        // 内网服务之前调用, 设置源为内网, 这样可以解决, Resp 类适配不同响应格式的问题
        template.header(SecurityCons.FROM_SOURCE, SecurityCons.FROM_IN);
        template.header(RequestCons.Headers.TENANT_ID, String.valueOf(TenantContext.get().getTenantId()));
        template.header(RequestCons.Headers.MAIN_TENANT_ID, String.valueOf(TenantContext.get().getMainTenantId()));

        // 非web 请求直接跳过
        if (!ServletUtils.getRequest().isPresent()) {
            return;
        }

        HttpServletRequest request = ServletUtils.getRequestOfNonNull();
        template.header(RequestCons.Headers.SYSTEM_TYPE, request.getHeader(RequestCons.Headers.SYSTEM_TYPE));
        template.header(RequestCons.Headers.LOGIN_USER, LoginUserHolder.get().encodeToString());
    }
}